const express = require('express');
const router = express.Router();
const { Article } = require('../../models')
const{ Op } = require('sequelize')
const {NotFoundError,success,failure} = require('../../utils/response')

//查询列表
router.get('/',async function(req, res, next) {
    try{
        const query = req.query
        //当前页数
        const currentPage = Math.abs(Number(query.currentPage))||1
        //每页显示条数
        const pageSize = Math.abs(Number(query.pageSize))||10 

        const offset = (currentPage-1)*pageSize
        const condition ={
            order:[['id','ASC']],
            limit:pageSize,
            offset:offset
        }
        if(query.title){
            condition.where = {
                title:{
                    [Op.like]:`%${query.title}%`
                }
            }
        }
        const {count,rows} = await Article.findAndCountAll(condition)
        success(res,'查询列表成功',{
            articles:rows,
            pagination:{
                total:count,
                currentPage:currentPage,
                pageSize:pageSize
            }
        },200)
    }catch(error){
        failure(res,error)
    }
    
});

//查询详情
router.get('/:id',async function(req, res, next) {
    try{
        const article = await getArticle(req)
        success(res,'查询成功',{ 
            article
        },201) 
    }catch(error){
        failure(res,error)
    }
    
});

//创建
router.post('/',async function(req, res, next) {
    try{
        //白名单过滤
        const body=filterBody(req)
        const article = await Article.create(body)
        success(res,"创建成功",{article},201) 
    }catch(error){
        failure(res,error)
    }
    
});

//删除
router.delete('/:id',async function(req, res, next) {
    try{
        const article = await getArticle(req)
        success(res,"删除文章成功。",{article},200)
    }catch(error){
        failure(res,error)
    }
    
});

//更新
router.put('/:id',async function(req, res, next) {
    try{
        const article = await getArticle(req)
        const body = filterBody(req)
        await article.update(body)
        res.json({
            status:true,
            message:"更新文章成功",
            data:article
        })  
    }catch(error){
        res.status(500).json({
            status:false,
            message:"更新文章失败",
            errors:[error.message]
        })
    }
    
});

//公共方法：查询
async function getArticle(req){
    const {id} = req.params
    //查询当前文章
    const article= await Article.findByPk(id)
    if(!article){
        throw new NotFoundError(`ID:${id}的文章未找到`)
    }
    return article
}

//白名单过滤
function filterBody(req){
    return{
        title:req.body.title,
        content:req.body.content
    }
}


module.exports = router;
